package commands;

import application.Core;
/**
 *	This class implements command shell.
 * 
 * @author Michal Mourek, Josef Vopalecký
 */
public class Shell extends AbstractCommand {
	/**
	 * Main method of this program.
	 * It launch the shell.
	 *
	 * @param parameters List of parameters entered by user in command line.
	 * @param arguments List of arguments entered by user in command line.
	 * @param id Process ID.
	 * @param core reference to the core
	 * @author Michal Mourek, Josef Vopalecký
	 */
	@Override
	public void main(String[] parameters, String[] arguments, int id, Core core) {
		if (parameters.length == 0){
			if (arguments.length == 0){
				while(!core.isEnd(id)){
					if(core.lastProccess(id)){
						if(core.canRead(id) == false){
							core.connectToGui(id);
						}
						else{
							String action = core.read(id);
							if(action != null && action != ""){
								core.runCommand(action,id);
							}
						}	
					}
					else{
						try {
							Thread.sleep(50);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}	
					}
				}
			}else{
				String[] arrayString = invalidArguments().split("\n");
				for (String string : arrayString) {
					core.write(id, string);
					try {
						Thread.sleep(50);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}

		}else {
			for(int i = 0; i < parameters.length; i++) {
				char parameter = parameters[i].charAt(1);
				if (parameter == 'h'){
					String[] help = help().split("\n");
					for (String string : help) {
						core.write(id, string);
						try {
							Thread.sleep(50);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					} 
				}else{
					String[] invalidParameters = invalidParameters().split("\n");
					for (String string : invalidParameters) {
						core.write(id, string);
						try {
							Thread.sleep(50);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
					break;
				}
			}
		}
	}
	
	/**
	 * Print help for this command.
	 *
	 * @author Michal Mourek
	 */
	@Override
	public String help() {
		return ("NAME: shell -  launch the shell \n SYNOPSYS: shell [OPTION] \n \n Description: \n   -h      print help \n");
		
		//throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
	}
	
	/**
	 * Print warning message, when parameter is invalid.
	 *
	 * @author Michal Mourek
	 */
	public String invalidParameters(){
		return ("Parameters is not correct \n Read help shell - h \n");
	}
	
	/**
	 * Print warning message, when argument is invalid.
	 *
	 * @author Michal Mourek
	 */
	public String invalidArguments(){
		return ("Arguments is not correct \n Read help shell - h \n");
	}
}
